/*
 * $RCSfile: Console.java,v $
 * $Revision: 1.1 $
 * $Date: 2010-06-21 $
 *
 * Copyright (C) 2008 Skin, Inc. All rights reserved.
 *
 * This software is the proprietary information of Skin, Inc.
 * Use is subject to license terms.
 */
package com.skin.demon;

import java.io.IOException;

import com.skin.app.CommandLine;
import com.skin.config.Arguments;

/**
 * <p>Title: Console</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2006</p>
 * @author xuesong.net
 * @version 1.0
 */
public class Console {
    private BeanFactory beanFactory;

    /**
     * @param args
     */
    public static void main(String[] args) {
        new Console().start();
    }

    /**
     * 
     */
    public void start() {
        CommandLine cmd = new CommandLine() {
            @Override
            protected Object execute(Object context, String command) throws Exception {
                return Console.this.execute(command);
            }
        };

        try {
            cmd.start();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param command
     * @return Object
     * @throws Exception 
     */
    public Object execute(String command) throws Exception {
        String serviceName = null;
        String methodName = null;
        String[] args = null;

        /**
         * junit@com.skin.test.manager.UserManagerTest.testProcess "a" "b"
         * @DateUtil.format 12345 "yyyy-MM-dd HH:mm:ss"
         * systemConfig.setXXX true
         */
        int k = command.indexOf(" ");

        if(k > -1) {
            serviceName = command.substring(0, k);
            args = Arguments.parse(command.substring(k + 1));
        }
        else {
            serviceName = command;
            args = new String[0];
        }

        k = serviceName.lastIndexOf(".");

        if(k < 0) {
            throw new Exception("bad command: " + serviceName);
        }

        methodName = serviceName.substring(k + 1).trim();
        serviceName = serviceName.substring(0, k).trim();
        new ServiceInvocation(this.getBeanFactory()).execute(serviceName, methodName, args);
        System.out.println("run " + serviceName + "." + methodName + " complete.");
        return null;
    }

    /**
     * @return BeanFactory
     */
    public BeanFactory getBeanFactory() {
        if(this.beanFactory == null) {
            this.beanFactory = new BeanFactory() {
                @Override
                public Object getBean(String name) {
                    return null;
                }
            };
        }
        return this.beanFactory;
    }
}
